package util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.KeyStore;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.net.ssl.SSLContext;
import javax.print.DocFlavor.URL;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jdom.JDOMException;
import org.jsoup.Connection.Method;
import org.springframework.http.HttpMethod;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayTradeCancelRequest;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeCancelResponse;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;


public class RefundTest {
	
	
	
	public static void main(String[] args) throws Exception {
		String out_no = "18041212004760715003000000002351";
		String refund_no = "18041213431948108696";
		String fee = "39800";
		
		//refundApli(out_no,refund_no,fee);
		
		//refundApli(out_no,refund_no,fee);
		refundWechat(out_no,refund_no,fee);
		//refundWechatWeb(out_no,refund_no,fee);
		
		//getAliMsg();
	}
	
	public static String Wechatrefund(String data) throws Exception{
		KeyStore keyStore  = KeyStore.getInstance("PKCS12");
		String file_name = "D:/refund/apiclient_cert.p12";
	//	String file_name = "D:/refund/apiclient_cert_public.p12";
        FileInputStream instream = new FileInputStream(new File(file_name));
        try {
            keyStore.load(instream, ConfigUtil.WECHAT_MCH_ID.toCharArray());
        } finally {
            instream.close();
        }

        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore,  ConfigUtil.WECHAT_MCH_ID.toCharArray())
                .build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                new String[] { "TLSv1" },
                null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();
        try {

            HttpPost httpget = new HttpPost(ConfigUtil.WECHAT_REFUND_URL);
            StringEntity entity1 = new StringEntity(data);
            httpget.setEntity(entity1);
            System.out.println("executing request" + httpget.getRequestLine());

            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                HttpEntity entity = response.getEntity();

                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                if (entity != null) {
                    System.out.println("Response content length: " + entity.getContentLength());
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                    String text;
                    while ((text = bufferedReader.readLine()) != null) {
                        System.out.println(text);
                    }
                   
                }
                String jsonStr = EntityUtils.toString(response.getEntity(),"UTF-8");
               
                EntityUtils.consume(entity);
                return jsonStr;
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
	}
	
	public static String WechatrefundWeb(String data) throws Exception{
		KeyStore keyStore  = KeyStore.getInstance("PKCS12");
		// test/apiclient_cert_public_test
		//String file_name = "D:/refund/apiclient_cert_public.p12";
		String file_name = "D:/refund/test/apiclient_cert_public.p12";
        FileInputStream instream = new FileInputStream(new File(file_name));
        try {
            keyStore.load(instream, ConfigUtil.WECHAT_WEB_MCH_ID.toCharArray());
        } finally {
            instream.close();
        }

        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore,  ConfigUtil.WECHAT_WEB_MCH_ID.toCharArray())
                .build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                new String[] { "TLSv1" },
                null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();
        try {

            HttpPost httpget = new HttpPost(ConfigUtil.WECHAT_REFUND_URL);
            StringEntity entity1 = new StringEntity(data);
            httpget.setEntity(entity1);
            System.out.println("executing request" + httpget.getRequestLine());

            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                HttpEntity entity = response.getEntity();

                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                if (entity != null) {
                    System.out.println("Response content length: " + entity.getContentLength());
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                    String text;
                    while ((text = bufferedReader.readLine()) != null) {
                        System.out.println(text);
                    }
                   
                }
                String jsonStr = EntityUtils.toString(response.getEntity(),"UTF-8");
               
                EntityUtils.consume(entity);
                return jsonStr;
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
	}

	
	public static void refundApli(String out_no,String refund_no,String fee) throws AlipayApiException{
		//支付宝退款
				AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
						ConfigUtil.ALIPAY_APP_ID, ConfigUtil.ALIPAY_APP_PRIVATE_KEY, "json", ConfigUtil.ALIPAY_CHARSET,
						ConfigUtil.ALIPAY_PUBLIC_KEY, "RSA2");

				AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
				AlipayTradeRefundModel model = new AlipayTradeRefundModel();
				model.setOutTradeNo(out_no);//out_trade_no
				model.setOutRequestNo(refund_no);//out_refund_no
				
				model.setRefundAmount(fee);//refund_fee
				request.setBizModel(model);
				
				AlipayTradeRefundResponse response = alipayClient.execute(request);

				if (response.isSuccess()) {
					System.out.println("调用成功");
					System.out.println(response.getOutTradeNo());
					System.out.println(response.getRefundFee());
				} else {
					System.out.println("调用失败");
				}
	}
	
	public static void refundWechat(String out_no,String refund_no,String fee) throws Exception{
		SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
		parameters.put("appid", ConfigUtil.WECHAT_APPID); //WECHAT_WEB_APPID     WECHAT_APPID
		parameters.put("mch_id", ConfigUtil.WECHAT_MCH_ID); //WECHAT_WEB_MCH_ID   WECHAT_MCH_ID
		parameters.put("nonce_str", PayCommonUtil.CreateNoncestr());
		parameters.put("out_refund_no", refund_no);
		parameters.put("out_trade_no", out_no); // 订单id
																			// 唯一
		parameters.put("refund_fee", fee);
		parameters.put("total_fee", fee);
		parameters.put("transaction_id", "");

		Map<String, Object> resultMap = new HashMap<String, Object>();
//		----2.根据package生成签名sign---- 
		String sign = PayCommonUtil.createSign("UTF-8", parameters); //createSignWeb

		parameters.put("sign", sign);
		String requestXML = PayCommonUtil.getRequestXml(parameters);
		String retur = Wechatrefund(requestXML);
		System.out.println(retur);
		Map<String, String> map = XMLUtil.doXMLParse(retur);
		
	}
	
	public static void refundWechatWeb(String out_no,String refund_no,String fee) throws Exception{
		SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
		parameters.put("appid", ConfigUtil.WECHAT_WEB_APPID); //WECHAT_WEB_APPID     WECHAT_APPID
		parameters.put("mch_id", ConfigUtil.WECHAT_WEB_MCH_ID); //WECHAT_WEB_MCH_ID   WECHAT_MCH_ID
		parameters.put("nonce_str", PayCommonUtil.CreateNoncestr());
		parameters.put("out_refund_no", refund_no);
		parameters.put("out_trade_no", out_no); // 订单id
																			// 唯一
		parameters.put("refund_fee", fee);
		parameters.put("total_fee", fee);
		parameters.put("transaction_id", "");

		Map<String, Object> resultMap = new HashMap<String, Object>();
//		----2.根据package生成签名sign---- 
		String sign = PayCommonUtil.createSignWeb("UTF-8", parameters); //createSignWeb

		parameters.put("sign", sign);
		String requestXML = PayCommonUtil.getRequestXml(parameters);
		String retur = WechatrefundWeb(requestXML);
		System.out.println(retur);
		Map<String, String> map = XMLUtil.doXMLParse(retur);
	}
	
	public static void getAliMsg() throws AlipayApiException{
		
		//支付宝退款
	/*	AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
				ConfigUtil.ALIPAY_APP_ID, ConfigUtil.ALIPAY_APP_PRIVATE_KEY, "json", ConfigUtil.ALIPAY_CHARSET,
				ConfigUtil.ALIPAY_PUBLIC_KEY, "RSA2");

		AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
		AlipayTradeRefundModel model = new AlipayTradeRefundModel();
		model.setOutTradeNo(out_no);//out_trade_no
		model.setOutRequestNo(refund_no);//out_refund_no
		
		model.setRefundAmount(fee);//refund_fee
		request.setBizModel(model);
		
		AlipayTradeRefundResponse response = alipayClient.execute(request);

		if (response.isSuccess()) {
			System.out.println("调用成功");
			System.out.println(response.getOutTradeNo());
			System.out.println(response.getRefundFee());
		} else {
			System.out.println("调用失败");
		}*/
		
		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
				ConfigUtil.ALIPAY_APP_ID, ConfigUtil.ALIPAY_APP_PRIVATE_KEY, "json", ConfigUtil.ALIPAY_CHARSET,
				ConfigUtil.ALIPAY_PUBLIC_KEY, "RSA2");
		AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
		request.setBizContent("{" +
		"\"out_trade_no\":\"18041212181886190981000000002356\"" +
	
		"}");
		AlipayTradeQueryResponse response = alipayClient.execute(request);
		System.out.println(response.getBody());
		if(response.isSuccess()){
		System.out.println("调用成功");
		} else {
		System.out.println("调用失败");
		}
	}
	
	
}
